package com.example.roles_management_p1.service.Impl;

import com.example.roles_management_p1.service.IRolesService;
import com.pojo.Entity.Roles;
import com.pojo.dto.ToRoles;
import com.pojo.mapper.RolesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RolesServiceImpl implements IRolesService {
    private static final String Roles_KEY="RolesKey";
    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    private static final String IDENTIFYING="identifying";
    @Override
    public Integer add(HttpServletRequest httpServletRequest, Roles roles) {
        Integer uID= (Integer) redisTemplate.opsForHash().get(httpServletRequest.getHeader(IDENTIFYING),"uID");
        roles.setRID(uID);
        Integer count=rolesMapper.insert(roles);
        redisTemplate.opsForValue().set(Roles_KEY+":"+uID,roles,120, TimeUnit.MINUTES);
        return count;
    }

    @Override
    public Integer isexist(HttpServletRequest httpServletRequest) {
        String identifying=httpServletRequest.getHeader(IDENTIFYING);
        Integer rID= (Integer) redisTemplate.opsForHash().get(identifying,"uID");
        if(rolesMapper.findByrID(rID)==null){
            return -1;
        }
        return (Integer) redisTemplate.opsForHash().get(identifying,"uType");
    }

    @Override
    public Integer update(HttpServletRequest httpServletRequest,Roles roles) {
        return null;
    }

    @Override
    public Roles getroles(Integer rID) {
        return rolesMapper.findByrID(rID);
    }

    @Override
    public List<ToRoles> getlroles(Integer Page, Integer Number, Integer uState) {
        Page=(Page-1)*Number;
        if(uState==null)
            return rolesMapper.findnolRoles(Page,Number);

        return rolesMapper.findlRoles(Page,Number,uState);
    }

    @Override
    public Integer delete(Integer rID) {
        return rolesMapper.delete(rID);
    }

    @Override
    public Roles getmyroles(HttpServletRequest httpServletRequest) {
        return rolesMapper.findByrID((Integer) redisTemplate.opsForHash().get(httpServletRequest.getHeader(IDENTIFYING),"uID"));
    }
}
